﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;

namespace TestForm.entity
{
    public static class Extensions
    {
        public static DataTable ToDataTable<T>(this List<T> items)
        {
            DataTable dataTable = new DataTable(typeof(T).Name);

            // 获取类型的所有公共属性
            PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

            // 将属性添加到DataTable的列中
            foreach (PropertyInfo prop in properties)
            {
                dataTable.Columns.Add(prop.Name, prop.PropertyType);
            }

            // 将列表中的每个对象的属性值填充到DataTable的行中
            foreach (T item in items)
            {
                DataRow row = dataTable.NewRow();

                foreach (PropertyInfo prop in properties)
                {
                    row[prop.Name] = prop.GetValue(item,null);
                }

                dataTable.Rows.Add(row);
            }

            return dataTable;
        }
    }
}
